package com.ecarx.camera.worker.camera.timer;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import com.ecarx.camera.constant.Constants;
import com.ecarx.camera.worker.event.RecordingTimerEvent;
import com.jeremyliao.liveeventbus.LiveEventBus;

/**
 * 录像计时Handler
 */
public class RecordingTimerHelper {

    private static final int MSG_WHAT_VIDEO_RECORDING = 1;

    private final Handler mMainHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_WHAT_VIDEO_RECORDING:
                    int hoursInt = msg.arg1 / 3600;
                    String hours = (hoursInt < 10 ? "0" : "") + hoursInt;
                    String minutes = "0" + (msg.arg1 % 3600) / 60;
                    minutes = minutes.substring(minutes.length() - 2);
                    String seconds = "0" + (msg.arg1 % 3600) % 60;
                    seconds = seconds.substring(seconds.length() - 2);

                    // 发送计时Event
                    LiveEventBus.get(RecordingTimerEvent.class).post(new RecordingTimerEvent(mFacingType, hours, minutes, seconds));

                    Message message = Message.obtain();
                    message.what = MSG_WHAT_VIDEO_RECORDING;
                    message.arg1 = msg.arg1 + 1;
                    mMainHandler.sendMessageDelayed(message, 999L);
                    break;
                default:
                    break;
            }
        }
    };

    private @Constants.FacingType int mFacingType;

    public RecordingTimerHelper(@Constants.FacingType int facingType) {
        this.mFacingType = facingType;
    }

    /**
     * 开始计时
     */
    public void start() {
        stop();
        Message message = Message.obtain(mMainHandler, MSG_WHAT_VIDEO_RECORDING);
        message.arg1 = 0;
        message.sendToTarget();
    }

    /**
     * 停止计时
     */
    public void stop() {
        if (mMainHandler.hasMessages(MSG_WHAT_VIDEO_RECORDING)) {
            mMainHandler.removeMessages(MSG_WHAT_VIDEO_RECORDING);
        }
    }
}
